
/*
 * Copyright (c) China Telecom Cloud Technology Co., Ltd. 2024-2025. All rights reserved.
 */
#include "ConfigLoader.h"
#include <fstream>
#include <cctype>

using namespace std;

string ConfigLoader::trim(const string &str) {
    if (str.empty())
        return str;

    auto start = str.begin();
    auto end = str.end();

    while (start != end && isspace(static_cast<unsigned char>(*start)))
        start++;

    if (start == end)
        return string();

    do {
        end--;
    } while (isspace(static_cast<unsigned char>(*end)));

    return string(start, end + 1);
}




void ConfigLoader::process_config_line(const string &line, 
                    unordered_map<string, string> &map) {
    string trimmed_line = trim(line);
    if (trimmed_line.empty()   || 
        trimmed_line[0] == '#' || 
        trimmed_line[0] == ';')
        return;

    size_t pos = trimmed_line.find('=');
    if (pos == string::npos)
        return;

    string key   = trim(trimmed_line.substr(0, pos));
    string value = trim(trimmed_line.substr(pos + 1));

    if (!key.empty()) {
        map[key] = value;
    }
}



const unordered_map<string, string> &ConfigLoader::get_config_map()
{
    //! static 变量只会初始化一次
    static const auto config_map = [] {
        unordered_map<string, string> map;
        ifstream file("config.ini");
        if (!file.is_open())
            return map;  // 文件不存在时返回空map

        // 依次读取每一行解析配置参数
        string line;
        while (getline(file, line)) {
            process_config_line(line, map);
        }
        return map;
    }();
    return config_map;
}